// miniprogram/pages/participate/index.js

import {
  authorize
} from '../../api/user.js'

import {
  subscribeLotteryMessage
} from '../../api/subscribe.js'

import {
  queryLottery,
  participate,
  queryParticipatedUsers
} from '../../api/lottery.js'

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    lotteryId: '',
    user: undefined,
    lottery: undefined,
    subscribeAlwaysGuideDisplaying: false,
    subscribeSettingGuideDisplaying: true,
    resultDialogDisplaying: false,
    authorized: true,
    avatars: [],
    poster: {
      width: 320,
      height: 980
    }
  },

  onParticipate(e) {

    if (app.authorized !== true) {
      wx.navigateTo({
        url: '/pages/authorize/index'
      });
      return;
    }

    wx.showLoading({
      title: '报名中',
      mask: true
    });

    participate(this.data.lotteryId).then(res => {
      if (res.result.errMsg === 'lottery-participate:error') {
        if (res.result.errCode === -1) {
          wx.showToast({
            title: "系统异常",
            icon: "none"
          });
          return;
        }
        if (res.result.errCode === 10001) {
          wx.showToast({
            title: "抽奖不存在",
            icon: "none"
          });
          return;
        }
        if (res.result.errCode === 10002) {
          wx.showToast({
            title: "抽奖已结束",
            icon: "none"
          });
          return;
        }
        if (res.result.errCode === 10003) {
          wx.showToast({
            title: "请勿重复报名",
            icon: "none"
          });
          return;
        }
      }

      if (res.result.errMsg === 'lottery-unauthorized:error') {
        wx.hideLoading();
        wx.navigateTo({
          url: '/pages/authorize/index'
        });
        return;
      }

      if (res.result.errMsg === 'lottery-participate:ok') {
        wx.showToast({
          title: "报名成功",
          icon: "none"
        });
        this.data.avatars.unshift(app.userInfo.avatarUrl);
        if (this.data.avatars.length > 20) {
          this.data.avatars.pop();
        }
        this.setData({
          user: this.data.user,
          'lottery.enrollments': res.result.data.lottery.enrollments,
          avatars: this.data.avatars
        });
      }

      if (res.result.data !== undefined && res.result.data.lottery.status === -1) {

        // 已开奖
        wx.showLoading({
          title: '正在开奖',
          mask: true
        });

        this.data.lottery.status = res.result.data.lottery.status;
        this.data.lottery.winners = res.result.data.lottery.winners;
        this.data.lottery.enrollments = res.result.data.lottery.enrollments;
        this.data.user.miss = res.result.data.user.miss;
        this.data.user.participated = res.result.data.user.participated;
        this.data.user.rewardCode = res.result.data.user.rewardCode;

        this.setData({
          user: this.data.user,
          lottery: this.data.lottery
        });

        setTimeout(() => {
          wx.hideLoading();
          this.setData({
            resultDialogDisplaying: true
          });
        }, 1000);

      } else {

        this.setData({
          'user.participated': true
        });

      }

    }).catch(res => {

      wx.showToast({
        title: "系统出错",
        icon: "none"
      });

    });

    let subscribeId = app.getSubscribeId("lottery-message-remind");
    let that = this;
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        let subscriptionsSetting = res.subscriptionsSetting;
        if (subscriptionsSetting === undefined) {
          console.log("没有申请过订阅消息");
          that.subscribeMessage(subscribeId);
          return;
        }
        let itemSettings = subscriptionsSetting.itemSettings;
        if (itemSettings === undefined) {
          console.log("询问用户是否订阅");
          that.setData({
            subscribeAlwaysGuideDisplaying: true
          });
          that.subscribeMessage(subscribeId);
          return;
        }
        if (res.authSetting["scope.subscribeMessage"] === false || subscriptionsSetting.mainSwitch === false || itemSettings[subscribeId] === "reject") {
          // 拒绝订阅且总是保持以上选择，不再询问
          console.log("拒绝订阅且总是保持以上选择，不再询问");
          wx.hideLoading();
          // 前往订阅指引
          wx.showModal({
            title: '提示',
            content: '你可能不小心关闭了订阅消息，不用担心，去设置开启就好啦',
            confirmText: '前往开启',
            cancelText: '返回',
            success: res => {
              if (res.confirm) {
                wx.openSetting();
              }
            }
          });
          return;
        }
        if (itemSettings[subscribeId] === "accept") {
          // 总是允许不再询问
          console.log("允许订阅且总是保持以上选择，不再询问");
          that.subscribeMessage(subscribeId);
          return;
        }
        console.log("询问用户是否订阅");
        that.setData({
          subscribeAlwaysGuideDisplaying: true
        });
        that.subscribeMessage(subscribeId);
      }
    });

  },

  subscribeMessage(subscribeId) {

    let subscribeAlwaysGuideDisplaying = this.data.subscribeAlwaysGuideDisplaying;
    let that = this;
    let lotteryId = this.data.lotteryId;
    wx.requestSubscribeMessage({
      tmplIds: [subscribeId],
      complete(res) {

        if (subscribeAlwaysGuideDisplaying) {
          that.setData({
            subscribeAlwaysGuideDisplaying: false
          });
        }

        if (res.errMsg === "requestSubscribeMessage:ok") {

          if (res[subscribeId] === "accept") {

            wx.showLoading({
              title: '请稍后',
              mask: true
            });

            subscribeLotteryMessage(subscribeId, lotteryId).then(res => {

              // 订阅成功
              if (res.result.errMsg === 'subscribe.lottery:ok') {

                if (subscribeAlwaysGuideDisplaying) {
                  wx.showToast({
                    title: "订阅消息成功",
                    icon: "none"
                  });
                }

              }


            });
          } else {

            wx.hideLoading();

          }

        }

      }
    });

  },

  onTapMore() {

    app.navigateHome();

  },

  prevent(e) {},

  onHideResultDialog() {

    this.setData({
      resultDialogDisplaying: false
    });

  },

  onDisplayResultDialog() {

    this.setData({
      resultDialogDisplaying: true
    });

  },

  onContact(e) {

    wx.setClipboardData({
      data: this.data.user.rewardCode,
      success: function (res) {
        wx.showToast({
          title: '兑奖码已复制',
          icon: 'none'
        });
      }
    });

  },

  onGetUserInfo(e) {

    if (e.detail.errMsg === "getUserInfo:ok") {

      authorize(e.detail.userInfo).then(res => {

        if (res.result.errMsg === 'user.authorize.ok') {

          app.authorized = true;
          this.setData({
            authorized: true
          });
          wx.showToast({
            title: '授权成功',
            icon: 'none'
          });

        }

      });

    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      lotteryId: options.lotteryId,
      authorized: app.authorized
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    queryLottery(this.data.lotteryId).then(res => {

      if (res.result.data.lottery.status === -1) {

        this.setData({
          user: res.result.data.user,
          lottery: res.result.data.lottery
        });

        setTimeout(() => {

          this.setData({
            loading: false
          });

          wx.nextTick(() => {
            this.setData({
              resultDialogDisplaying: true
            });
          });

        }, 500);

        return;

      }

      this.setData({
        loading: false,
        user: res.result.data.user,
        lottery: res.result.data.lottery
      });

      queryParticipatedUsers(1, 20, this.data.lotteryId).then(res => {

        wx.hideNavigationBarLoading();
        if (res.result.errMsg === 'query-participated-users-page:none') {
          this.setData({
            avatars: []
          });
          return;
        }
        this.setData({
          avatars: res.result.data.avatars
        });

      });

    });

  },

  onTapSponsor() {

    if (this.data.lottery.sponsor.appId !== undefined) {
      wx.navigateToMiniProgram({
        appId: this.data.lottery.sponsor.appId
      });
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

    return {
      title: (this.data.lottery.share.sponsor ? this.data.lottery.share.sponsor : (app.userInfo.nickName === undefined ? '' : app.userInfo.nickName)) + '@你来抽“' + (this.data.lottery.share.title ? this.data.lottery.share.title : this.data.lottery.rewards.map(reward => reward.name).join("；").toString()) + '”',
      path: '/pages/index/index?lotteryId=' + this.data.lotteryId,
      imageUrl: this.data.lottery.share.imageUrl
    }

  }

})